<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺地址" prop="shopAddress">
        <el-input
          v-model="queryParams.shopAddress"
          placeholder="请输入店铺地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['milktea:shop:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['milktea:shop:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['milktea:shop:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['milktea:shop:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="shopList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="shopId" />
      <el-table-column label="店铺缩略图" align="center" prop="shopImage">
        <template slot-scope="scope">
          <img :src="scope.row.shopImage" style="width: 50px; heigth: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="店铺地址" align="center" prop="shopAddress" />
      <el-table-column label="状态" align="center" prop="shopState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.shopState"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['milktea:shop:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['milktea:shop:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商店管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择用户" prop="shopSysUserName">
           
          <el-select
            v-model="form.shopSysUserName"
            placeholder="请选择用户"
          >
            <el-option
              v-for="(item, index) in sysUser"
              :key="index"
              :label="item.userName"
              :value="item.userId"
            />
                   
          </el-select>
        </el-form-item>
        <el-form-item label="店铺缩略图">
          <imageUpload v-model="form.shopImage" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="营业开始时间" prop="shopBusinessStartHours">
          <el-time-select placeholder="起始时间" v-model="form.shopBusinessStartHours" :picker-options="{
              start: '08:30',
              step: '00:15',
              end: '18:30'
            }">
          </el-time-select>
        </el-form-item>
        <el-form-item label="营业结束时间" prop="shopBusinessEndHours">
          <el-time-select placeholder="结束时间" v-model="form.shopBusinessEndHours" :picker-options="{
              start: '08:30',
              step: '00:15',
              end: '18:30',
              minTime: form.shopBusinessStartHours
            }">
          </el-time-select>
        </el-form-item>
        <el-form-item label="地理位置" prop="address">
          <el-input v-model="form.shopAddress" disabled placeholder="请输入地理位置" />

          <el-button type="text" @click="dialogVisible = true"
            >请选择商店位置</el-button
          >

          <el-dialog
            title="请选择申请商家位置"
            :visible.sync="dialogVisible"
            width="50%"
            style="height: 1000px"
            :before-close="handleClose"
            :modal-append-to-body="false"
            append-to-body
          >
            <div id="div">
              <div class="select">
                <!--查询结果(经纬度)：<input id="result_" type="text" :value="lng"+"lat" />-->
                <el-input
                  id="text_"
                  v-model="form.shopAddress"
                  placeholder="请输店铺名称"
                  name="address"
                ></el-input>
                <!-- 搜索按钮 -->
                <el-button
                  icon="el-icon-search"
                  v-on:click="searchByStationName()"
                  circle
                  class="select_btn"
                ></el-button>
              </div>
              <div id="container"></div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="dialogVisible = false"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.shopState">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  SysUser,
  listShop,
  getShop,
  delShop,
  addShop,
  updateShop,
} from "@/api/milktea/shop";

export default {
  name: "Shop",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // map
      dialogVisible: false,
      location: [(lng) => "", (lat) => ""],
      val: "",
      // 修改下拉框
      userId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商店管理表格数据
      shopList: [],
      // 用户
      sysUser: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: null,
        shopAddress: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  mounted() {
    this.index();
  },
  created() {
    this.getList();
  },
  updated() {
    this.$nextTick(() => {
      var map = new BMap.Map("container", {
        enableMapClick: true,
      }); // 创建Map实例
      map.centerAndZoom(new BMap.Point(116.413387, 39.910924), 11); // 初始化地图,设置中心点坐标和地图级别
      //添加地图类型控件
      map.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
        })
      );
      map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      const _this = this;
      map.addEventListener("click", function (e) {
        _this.location.lng = parseFloat(e.point.lng).toFixed(3);
        _this.location.lat = parseFloat(e.point.lat).toFixed(3);
        console.log(_this.location.lng,_this.location.lat);
        _this.form.shopLongitude = _this.location.lng;
        _this.form.shopLatitude = _this.location.lat;
      });
    });
  },
  methods: {
    //map
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    setmap: function () {
      this.$nextTick(() => {
        var map = new BMap.Map("container", {
          enableMapClick: true,
        }); // 创建Map实例
        map.centerAndZoom(new BMap.Point(116.413387, 39.910924), 11); // 初始化地图,设置中心点坐标和地图级别
        //添加地图类型控件
        map.addControl(
          new BMap.MapTypeControl({
            mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
          })
        );
        map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的
        map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
        const _this = this;
        map.addEventListener("click", function (e) {
          _this.location.lng = parseFloat(e.point.lng).toFixed(3);
          _this.location.lat = parseFloat(e.point.lat).toFixed(3);
        });
      });
    },
    
    searchByStationName: function () {
      var _this = this;
      var map = new BMap.Map("container", {
        enableMapClick: true,
      }); // 创建Map实例
      map.clearOverlays(); //清空原来的标注
      var localSearch = new BMap.LocalSearch(map);
      localSearch.enableAutoViewport(); //允许自动调节窗体大小
      var keyword = document.getElementById("text_").value;
      localSearch.setSearchCompleteCallback(function (searchResult) {
        var poi = searchResult.getPoi(0);
        //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
        map.centerAndZoom(poi.point, 13);
        var marker = new BMap.Marker(
          new BMap.Point(poi.point.lng, poi.point.lat)
        ); // 创建标注，为要查询的地方对应的经纬度
        map.addOverlay(marker);
        // document.getElementById("lngs").value = poi.point.lng;
        // document.getElementById("lats").value = poi.point.lat;
        _this.form.shopLongitude = poi.point.lng;
        _this.form.shopLatitude = poi.point.lat;
        marker.addEventListener("click", function () {
          this.openInfoWindow(infoWindow);
        });
        marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      });
      localSearch.search(keyword);
    },
    index: function () {
      $.ajax({
        url: "",
        dataType: "json",
        type: "get",
        success: function (date) {
          date.forEach(function (v) {
            $("#sheng").append(
              "<option value='" + v.Id + "'>" + v.Name + "</option>"
            );
          });
        },
      });
    },
    /** 查询商店管理列表 */
    getList() {
      this.loading = true;
      listShop(this.queryParams).then((response) => {
        this.shopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      SysUser().then((response) => {
        this.sysUser = response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        shopId: null,
        shopImage: null,
        shopName: null,
        shopAddress: null,
        shopLongitude: null,
        shopLatitude: null,
        shopState: 0,
        shopSysUserName: null,
        shopBusinessStartHours:null,
        shopBusinessEndHours:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.shopId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商店管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const shopId = row.shopId || this.ids;
      getShop(shopId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商店管理";
        this.form.shopSysUserName = response.data.sysUsere.userName;
        // response.data.sysUsere.userName
        this.userId = response.data.sysUsere.userId;
        console.log("form:",this.form);
        console.log("userId:",this.userId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.shopId != null) {
            var str = this.form.shopSysUserName;
            if(typeof str == 'string'){
              this.form.shopSysUserName = this.userId;
            }
            updateShop(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShop(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const shopIds = row.shopId || this.ids;
      this.$modal
        .confirm('是否确认删除商店管理编号为"' + shopIds + '"的数据项？')
        .then(function () {
          return delShop(shopIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "milktea/shop/export",
        {
          ...this.queryParams,
        },
        `shop_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.el-dialog{
  width: 50% !important;
}
.el-form-item__label{
  width: 100px !important;
}
.el-form-item__content{
  margin-left: 100px !important;
}
#container {
  position: absolute;
  width: 730px;
  height: 360px;
  top: 50;
  border: 1px solid gray;
  overflow: hidden;
}

#text_ {
  margin-right: 100px;
  width: 300px;
}

#div {
  width: 730px;
  height: 400px;
  margin: auto;
}
.select{
  width: 350px;
  margin-bottom: 20px;
}
.select_btn{
  position: absolute;
  left: 330px;
}
</style>
